package com.dirk.happie.activities;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.dirk.happie.R;
import com.dirk.happie.adapters.AddressEditListAdapter;
import com.dirk.happie.beans.AddressBean;
import com.dirk.happie.network.RequestCompleteListener;
import com.dirk.happie.network.UpdateUserTask;
import com.dirk.happie.utils.App;
import com.dirk.happie.utils.Availablity;
import com.dirk.happie.utils.Keys;

public class ProfileActivity extends Activity {
	private Dialog alertDialog;
	private ToggleButton toggle_on_off;
	private Button logoutButton;
	private Button saveChanges;

	private EditText nameEditText;
	private EditText surnameEditText;
	private EditText emailEditText;
	private EditText streetEditText;
	private EditText aptnoEditText;
	private EditText zipEditText;
	private EditText cityEditText;
	private EditText phoneEditText;
	// private EditText countryEditText;

	private String password;
	private String name;
	private String surname;
	private String email;
	private String street;
	private String aptno;
	private String zip;
	private String city;
	private String phone;
	// private String country;

	private App mApp;

	private UpdateUserTask updateUserTask = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_profile);

		this.mApp = ((App) getApplication());

		address_data = new ArrayList<AddressBean>();

		// ImageView companyLogoView = (ImageView)
		// findViewById(R.id.img_company);

		createView();

		initListView();
		
		onOffButtonListener();
		// footerMenuListeners();
	}

	@Override
	protected void onResume() {

		nameEditText.setText(mApp.getHappie_prefs().getString(Keys.KEY_NAME, ""));
		surnameEditText.setText(mApp.getHappie_prefs().getString(Keys.KEY_SURNAME, ""));
		emailEditText.setText(mApp.getHappie_prefs().getString(Keys.KEY_USERNAME, ""));
		streetEditText.setText(mApp.getHappie_prefs().getString(Keys.KEY_STREET, ""));
		aptnoEditText.setText(mApp.getHappie_prefs().getString(Keys.KEY_APT_NO, ""));
		zipEditText.setText(mApp.getHappie_prefs().getString(Keys.KEY_ZIP, ""));
		cityEditText.setText(mApp.getHappie_prefs().getString(Keys.KEY_CITY, ""));
		phoneEditText.setText(mApp.getHappie_prefs().getString(Keys.KEY_PHONE, ""));
		// countryEditText.setText(mApp.getHappie_prefs().getString(Keys.KEY_COUNTRY,
		// ""));

		super.onResume();
	}
	
	private GestureDetector gestureDetector = null;
	
	private AddressBean addressToEdit;
	private int addressPosition;

	private void createView() {
		
		gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
			
			@Override
			public boolean onDoubleTapEvent(MotionEvent e) {
				showAddAddressDialog(addressToEdit, addressPosition);
				return super.onDoubleTapEvent(e);
			}

		});

		Button addAddress = (Button) findViewById(R.id.addButton);
		addAddress.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showAddAddressDialog(null, 0);
			}
		});

		TextView versionTextView = (TextView) findViewById(R.id.versionText);
		PackageInfo pInfo;
		String version = getString(R.string.app_name);
		try {
			pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
			version = "Version " + pInfo.versionName;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		versionTextView.setText(version);
		nameEditText = (EditText) findViewById(R.id.nameEdit);
		surnameEditText = (EditText) findViewById(R.id.surnameEdit);
		emailEditText = (EditText) findViewById(R.id.emailEdit);
		streetEditText = (EditText) findViewById(R.id.streetEdit);
		aptnoEditText = (EditText) findViewById(R.id.aptnoEdit);
		zipEditText = (EditText) findViewById(R.id.zipEdit);
		cityEditText = (EditText) findViewById(R.id.cityEdit);
		phoneEditText = (EditText) findViewById(R.id.phoneEdit);
		// countryEditText = (EditText) findViewById(R.id.countryEdit);

		logoutButton = (Button) findViewById(R.id.logoutButton);
		logoutButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				SharedPreferences.Editor editor = mApp.getHappie_prefs().edit();
				editor.putString(Keys.KEY_NAME, "");
				editor.putString(Keys.KEY_SURNAME, "");
				// editor.putString(Keys.KEY_EMAIL, "");
				editor.putString(Keys.KEY_STREET, "");
				editor.putString(Keys.KEY_APT_NO, "");
				editor.putString(Keys.KEY_ZIP, "");
				editor.putString(Keys.KEY_CITY, "");
				// editor.putString(Keys.KEY_COUNTRY, "");
				editor.putString(Keys.KEY_USER_ID, "");
				editor.putBoolean(Keys.KEY_USER_LOGGED_IN, false);
				editor.putString(Keys.KEY_USERNAME, "");
				editor.putString(Keys.KEY_PASSWORD, "");
				editor.putString(Keys.KEY_PHONE, "");
				editor.putString(Keys.KEY_ADDRESS, "");
				editor.putString(Keys.KEY_ADDRESSES, "[]");
				editor.putString("Favorites", "[]");
				editor.commit();

				mApp.setLoggedIn(false);
				mApp.setUserId("");
				mApp.getFavorites().removeAll(mApp.getFavorites());
				mApp.addDefaultFavorite();

				setResult(600);
				finish();
			}
		});

		saveChanges = (Button) findViewById(R.id.saveButton);
		saveChanges.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				password = mApp.getHappie_prefs().getString(Keys.KEY_PASSWORD, "");
				name = nameEditText.getText().toString();
				surname = surnameEditText.getText().toString();
				email = emailEditText.getText().toString();
				street = streetEditText.getText().toString();
				aptno = aptnoEditText.getText().toString();
				zip = zipEditText.getText().toString().replaceAll(" ", "");
				zipEditText.setText(zip);
				city = cityEditText.getText().toString();
				phone = phoneEditText.getText().toString();
				// country = countryEditText.getText().toString();
				boolean isEmpty = false;
				if (name.equals(Keys.EMPTY_STRING)) {
					nameEditText.setHintTextColor(getResources().getColor(R.color.red));
					isEmpty = true;
				}
				if (surname.equals(Keys.EMPTY_STRING)) {
					surnameEditText.setHintTextColor(getResources().getColor(R.color.red));
					isEmpty = true;
				}
				if (email.equals(Keys.EMPTY_STRING)) {
					emailEditText.setHintTextColor(getResources().getColor(R.color.red));
					isEmpty = true;
				}
				if (street.equals(Keys.EMPTY_STRING)) {
					streetEditText.setHintTextColor(getResources().getColor(R.color.red));
					isEmpty = true;
				}
				if (aptno.equals(Keys.EMPTY_STRING)) {
					aptnoEditText.setHintTextColor(getResources().getColor(R.color.red));
					isEmpty = true;
				}
				if (zip.equals(Keys.EMPTY_STRING)) {
					zipEditText.setHintTextColor(getResources().getColor(R.color.red));
					isEmpty = true;
				}
				if (city.equals(Keys.EMPTY_STRING)) {
					cityEditText.setHintTextColor(getResources().getColor(R.color.red));
					isEmpty = true;
				}
				if (phone.equals(Keys.EMPTY_STRING)) {
					phoneEditText.setHintTextColor(getResources().getColor(R.color.red));
					isEmpty = true;
				}
				if (isEmpty) {
					showErrorDialog(getString(R.string.fill_all_fields));
					return;
				}

				updateUser();

			}
		});

	}

	private void updateUser() {

		updateUserTask = new UpdateUserTask(ProfileActivity.this);

		updateUserTask.setRequestCompleteListener(new RequestCompleteListener<String>() {

			@Override
			public void onSuccess(String result) {
				SharedPreferences.Editor editor = mApp.getHappie_prefs().edit();
				try {
					JSONArray jsonArray = new JSONArray(result);
					JSONObject json = jsonArray.getJSONObject(0);
					if (json.has("apimsg")) {
						editor.putString(Keys.KEY_NAME, name);
						editor.putString(Keys.KEY_SURNAME, surname);
						editor.putString(Keys.KEY_EMAIL, email);
						editor.putString(Keys.KEY_STREET, street);
						editor.putString(Keys.KEY_APT_NO, aptno);
						editor.putString(Keys.KEY_ZIP, zip);
						editor.putString(Keys.KEY_CITY, city);
						editor.putString(Keys.KEY_PHONE, phone);
						// editor.putString(Keys.KEY_COUNTRY, country);
						editor.putString(Keys.KEY_ADDRESS, city + ", " + street + ", " + aptno + ", " + zip);
						editor.commit();

						showMessageDialog(json.getString("apimsg"));
						return;
					}

					if (json.has("error")) {
						showErrorDialog(json.getString("error"));
						return;
					}
				} catch (Exception e) {
				}
			}

			@Override
			public void onFailure(String message) {
				// TODO Auto-generated method stub

			}
		});
		if (Availablity.isNetworkAvailable(this)) {
			updateUserTask.execute(email, password, name, surname, street, aptno, zip, city, phone, mApp.getUserId());
		} else {
			Toast.makeText(this, getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
		}
	}

	public void showErrorDialog(String message) {
		if (alertDialog != null && alertDialog.isShowing())
			return;

		alertDialog = new Dialog(this);
		alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		alertDialog.setContentView(R.layout.dialog);
		alertDialog.setCancelable(true);

		TextView text = (TextView) alertDialog.findViewById(R.id.dialog_title);
		text.setTextSize(18);
		text.setText(message);

		Button okButton = (Button) alertDialog.findViewById(R.id.ok_button);
		okButton.setText(R.string.ok_error);
		okButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				alertDialog.cancel();
			}
		});
		alertDialog.show();
	}

	public void showMessageDialog(String message) {
		if (alertDialog != null && alertDialog.isShowing())
			return;

		alertDialog = new Dialog(this);
		alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		alertDialog.setContentView(R.layout.dialog);
		alertDialog.setCancelable(true);

		TextView text = (TextView) alertDialog.findViewById(R.id.dialog_title);
		text.setTextSize(18);
		text.setText(message);

		Button okButton = (Button) alertDialog.findViewById(R.id.ok_button);
		okButton.setText(R.string.ok_error);
		okButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				alertDialog.cancel();
			}
		});
		alertDialog.show();
	}

	private void onOffButtonListener() {

		toggle_on_off = (ToggleButton) findViewById(R.id.toggleOnOff);

		toggle_on_off.setChecked(false);
		if (toggle_on_off.isChecked()) {
			toggle_on_off.setBackgroundResource(R.drawable.on_btn);
		} else {
			toggle_on_off.setBackgroundResource(R.drawable.off_btn);
		}

		toggle_on_off.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked) {
					toggle_on_off.setBackgroundResource(R.drawable.on_btn);
				} else {
					toggle_on_off.setBackgroundResource(R.drawable.off_btn);
				}
			}

		});
	}

	public void showAddAddressDialog(final AddressBean bean, final int position) {
		if (alertDialog != null && alertDialog.isShowing())
			return;

		alertDialog = new Dialog(this);
		alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		alertDialog.setContentView(R.layout.dialog_change_address);
		alertDialog.setCancelable(true);

		final EditText cityEditTextDialog = (EditText) alertDialog.findViewById(R.id.cityEdit);

		final EditText streetEditTextDialog = (EditText) alertDialog.findViewById(R.id.streetEdit);

		final EditText aptEditTextDialog = (EditText) alertDialog.findViewById(R.id.aptnoEdit);

		final EditText zipEditTextDialog = (EditText) alertDialog.findViewById(R.id.zipEdit);

		if (bean != null) {
			cityEditTextDialog.setText(bean.getCity());
			streetEditTextDialog.setText(bean.getStreet());
			aptEditTextDialog.setText(bean.getApt());
			zipEditTextDialog.setText(bean.getZip());
		}

		Button okButton = (Button) alertDialog.findViewById(R.id.okButton);

		okButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				AddressBean beanNew = new AddressBean(cityEditTextDialog.getText().toString(), streetEditTextDialog.getText().toString(), aptEditTextDialog.getText().toString(), zipEditTextDialog.getText().toString().replaceAll(" ", ""));
				addAddress(beanNew, bean, position);
				initListView();
				alertDialog.cancel();
			}
		});

		Button cancelButton = (Button) alertDialog.findViewById(R.id.cancelButton);
		cancelButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				alertDialog.cancel();
			}
		});

		alertDialog.show();
	}

	private void addAddress(AddressBean beanNew, AddressBean beanOld, int position) {

		try {
			JSONArray addressArray = new JSONArray(mApp.getHappie_prefs().getString(Keys.KEY_ADDRESSES, "[]"));
			JSONObject json = new JSONObject();
			json.putOpt("street", beanNew.getStreet());
			json.putOpt("apt", beanNew.getApt());
			json.putOpt("zip", beanNew.getZip());
			json.putOpt("city", beanNew.getCity());
			if (beanOld == null) {

				addressArray.put(json);
				mApp.getHappie_prefs().edit().putString(Keys.KEY_ADDRESSES, addressArray.toString()).commit();
			} else {
				ArrayList<String> stringArray = new ArrayList<String>();
				for (int i = 0; i < addressArray.length(); i++) {
					stringArray.add(addressArray.getJSONObject(i).toString());
				}
				stringArray.remove(position);
				stringArray.add(position, json.toString());
				mApp.getHappie_prefs().edit().putString(Keys.KEY_ADDRESSES, stringArray.toString()).commit();
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void initListView() {

		getAddresses();

		LinearLayout lv = (LinearLayout) findViewById(R.id.listAddreses);
		lv.removeAllViews();
		AddressEditListAdapter adapter = new AddressEditListAdapter(this, R.layout.edit_address_list_item, address_data);
		int count = adapter.getCount();
		for (int i = 0; i < count; i++) {
			final int position = i;
			View view = adapter.getView(i, null, null);
			view.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					addressToEdit = address_data.get(position);
					addressPosition = position;
					gestureDetector.onTouchEvent(event);
					return true;
				}
			});
			lv.addView(view);

		}
	}

	ArrayList<AddressBean> address_data;

	private void getAddresses() {

		address_data.clear();

		try {
			JSONArray addressArray = new JSONArray(mApp.getHappie_prefs().getString(Keys.KEY_ADDRESSES, "[]"));
			for (int i = 0; i < addressArray.length(); i++) {
				JSONObject json = addressArray.getJSONObject(i);
				AddressBean address = new AddressBean();

				address.setCity(json.optString("city"));

				address.setStreet(json.optString("street"));

				address.setApt(json.optString("apt"));

				address.setZip(json.optString("zip"));

				address_data.add(address);

			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	// private void footerMenuListeners() {
	//
	// View homeButton = findViewById(R.id.home);
	// homeButton.setOnClickListener(new OnClickListener() {
	//
	// @Override
	// public void onClick(View v) {
	// finish();
	// }
	// });
	//
	// View categoriesButton = findViewById(R.id.categories);
	// categoriesButton.setOnClickListener(new OnClickListener() {
	//
	// @Override
	// public void onClick(View v) {
	// if (mApp.isLoggedIn()) {
	// Intent intent = new Intent(ProfileActivity.this,
	// CategoriesActivity.class);
	// intent.putExtra(Keys.KEY_COMPANY_ID, mApp.getCompanyId());
	// startActivityForResult(intent, 10);
	// } else {
	// Toast.makeText(getApplicationContext(),
	// getString(R.string.not_logged_in), Toast.LENGTH_SHORT).show();
	// }
	// }
	// });
	//
	// View basketButton = findViewById(R.id.basket);
	// basketButton.setOnClickListener(new OnClickListener() {
	//
	// @Override
	// public void onClick(View v) {
	//
	// if (mApp.isLoggedIn()) {
	// Intent intent = new Intent(ProfileActivity.this, BasketActivity.class);
	// intent.putExtra(Keys.KEY_COMPANY_ID, mApp.getCompanyId());
	// startActivityForResult(intent, 10);
	// } else {
	// Toast.makeText(getApplicationContext(),
	// getString(R.string.not_logged_in), Toast.LENGTH_SHORT).show();
	// }
	// }
	// });
	//
	// View searchButton = findViewById(R.id.search);
	// searchButton.setOnClickListener(new OnClickListener() {
	//
	// @Override
	// public void onClick(View v) {
	//
	// }
	// });
	//
	// }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == 100) {
			finish();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onPause() {

		super.onPause();
	}

	@Override
	protected void onDestroy() {
		if (updateUserTask != null) {
			updateUserTask.setRequestCompleteListener(null);
		}
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_settings, menu);
		return true;
	}

}
